<template>
  <div class="app-container">
    <vue-element-loading
      :active="this.$store.state.elementloading.vueElementLoading"
      spinner="spinner"
      color="#FF6700"
    />
    <el-card shadow="never">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchMap"
        style="margin-top: 20px;margin-left: 0px"
      >
        <el-form-item prop="companyName">
          <el-input @keyup.enter.native="searchcompany" v-model.lazy="searchMap.companyName">
            <template slot="prepend">公司名称</template>
          </el-input>
        </el-form-item>
        <el-button @click="searchcompany" icon="el-icon-search"></el-button>
      </el-form>

      <el-button-group style="margin-bottom:20px">
        <el-button v-if="btnshow('company-add')" @click="openNew" size="small" type="primary" icon="el-icon-plus"></el-button>
        <el-button v-if="btnshow('company-update')" @click="handleEdit(radio)" size="small" type="primary" icon="el-icon-edit"></el-button>
        <el-button v-if="btnshow('company-delete')" @click="deleteCompany(radio)" size="small" type="primary" icon="el-icon-delete"></el-button>
      </el-button-group>
      <template>
        <el-table
          :data="list"
          max-height="500"
          border
          style="width: 100%"
          @row-click="chooseone"
          highlight-current-row
          @current-change="handleSelectionChange"
        >
          <el-table-column width="55">
            <template slot-scope="scope">
              <el-radio v-model="radio" :label="scope.row.id">
                <span class="el-radio__label"></span>
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="cName" label="公司名称" width="140"></el-table-column>
          <el-table-column prop="cPerson" label="公司负责人" width="100"></el-table-column>
          <el-table-column prop="cContact" label="联系方式" width="130"></el-table-column>
          <el-table-column prop="cMedicinal" label="种植品种" align="center" width="150"></el-table-column>
          <el-table-column prop="cRemarks" label="公司简介" align="center"></el-table-column>
          <el-table-column fixed="right" prop="cPosition" label="公司位置" align="center"></el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 编辑公司信息弹窗 -->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        v-dialogDrag
        :title="title"
        :visible.sync="editdataDialog"
        width="40%"
      >
        <el-form
          :rules="rules"
          ref="editForm"
          :model="pojo"
          label-width="130px"
          label-position="right"
        >
          <el-form-item label="公司名称：" prop="cName">
            <!-- autocomplete="off"为 保存之前填过的值 -->
            <el-input v-model="pojo.cName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="公司负责人：" prop="cPerson">
            <el-input v-model="pojo.cPerson" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="负责人联系方式：" prop="cContact">
            <el-input v-model="pojo.cContact" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="公司位置：" prop="cPosition">
            <el-input type="textarea" rows="3" v-model="pojo.cPosition" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="种植药材：" prop="cMedicinal">
            <el-input type="textarea" rows="3" v-model="pojo.cMedicinal" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注(公司简介)：" prop="cRemarks">
            <el-input type="textarea" rows="4" v-model="pojo.cRemarks" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleData">取 消</el-button>
          <el-button @click="addData" type="primary">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import companyApi from "@/api/company";
import VueElementLoading from "vue-element-loading";
import { hasPermissionPoint } from "@/utils/permission";

export default {
  components: {
    VueElementLoading
  },
  data() {
    return {
      pojo: {
        id: "",
        cName: "",
        cPosition: "",
        cPerson: "",
        cContact: "",
        cMedicinal: "",
        cRemarks: ""
      },
      backup: {},
      list: [],
      total: 0, //总记录数
      currentPage: 1, //当前页码
      pageSize: 5, //每页显示5条数据
      radio: null, // 如果使用单选框，定义一个model值
      currentSelectItem: {}, //当前选中的值
      searchMap: {
        companyName: ""
      },
      editdataDialog: false,
      rules: {
        // 校验规则
        cName: [
          { required: true, message: "基地名称不能为空", trigger: "blur" }
        ]
      },
      title: ""
    };
  },

  created() {
    // 初始化获取列表数据
    this.searchBycompanyName();
  },

  methods: {
    btnshow(point) {
      return hasPermissionPoint(point);
    },
    chooseone(row) {
      this.radio = row.id;
      this.backup = this.pojo = row;
    },
    handleSelectionChange(row) {
      console.log(row);
      this.currentSelectItem = row;
    },
    // 当每页显示条数改变后，被触发，val是最新的显示条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.searchBycompanyName();
      // this.searchMap.companyName == null ? this.fetchData(): this.searchBycompanyName();
    },
    // 当页码改变后，被触发，val是最新的页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.searchBycompanyName();
      // this.searchMap.companyName == null ? this.fetchData(): this.searchBycompanyName2();
    },
    searchcompany() {
      this.currentPage = 1;
      this.searchBycompanyName();
    },
    // 根据公司名称查询
    searchBycompanyName() {
      var vm = this.$store;
      vm.commit("updateLoading", true);
      console.log(
        "是否开启加载",
        this.$store.state.elementloading.vueElementLoading
      );
      companyApi
        .selectCompany(
          this.searchMap.companyName,
          this.currentPage,
          this.pageSize
        )
        .then(resp => {
          this.list = resp.data.rows;
          this.total = resp.data.total;
          console.log("公司", resp.data.rows);
          if (resp.data.rows) {
            vm.commit("updateLoading", false);
            console.log(
              "是否开启加载",
              this.$store.state.elementloading.vueElementLoading
            );
          }
          // console.log(resp);
        });
    },
    // 打开新增弹窗
    openNew() {
      this.isEdit = false;
      this.openDialog(this.isEdit);
    },
    // 打开修改弹窗
    handleEdit(id) {
      if (id != null && id != "") {
        this.isEdit = true; // 切换为修改状态
        this.openDialog(this.isEdit);
        // this.fpojo
      } else {
        this.$message({
          message: "请选择需要修改的公司哦！",
          type: "warning"
        });
      }
    },

    handleDialogClose() {
      this.editdataDialog = false;
    },

    // 关闭编辑弹窗，并将值赋为空
    closeDialog() {
      this.editdataDialog = false;
      this.pojo = {
        id: "",
        cName: "",
        cPosition: "",
        cPerson: "",
        cContact: "",
        cMedicinal: "",
        cRemarks: ""
      };
      this.searchBycompanyName();
    },

    // 打开弹窗
    openDialog(e) {
      if (e) {
        this.pojo = this.backup;
        this.title = "修改公司";
      } else {
        this.title = "新增公司";
        this.pojo = {
          id: "",
          cName: "",
          cPosition: "",
          cPerson: "",
          cContact: "",
          cMedicinal: "",
          cRemarks: ""
        };
      }
      this.editdataDialog = true;
      // 请求校验规则
      this.$nextTick(() => {
        this.$refs["editForm"].clearValidate();
      });
    },

    // 取消上传表单
    cancleData() {
      this.closeDialog();
    },

    // 提交表单
    addData() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // 修改
            companyApi.updateCompany(this.pojo).then(resp => {
              if (resp.data.flag) {
                //修改成功
                this.$message({
                  message: "修改公司信息成功",
                  type: "success"
                });
                // 关闭
                this.closeDialog();
                // 刷新数据
              } else {
                // 失败
                this.$message({
                  message: "修改公司信息失败",
                  type: "warning"
                });
              }
            });
          } else {
            companyApi.insertCompany(this.pojo).then(resp => {
              if (resp.data.flag) {
                //新增成功
                this.$message({
                  message: "新增公司信息成功",
                  type: "success"
                });
                // 关闭
                this.closeDialog();
              } else {
                // 失败
                this.$message({
                  message: "新增公司信息失败",
                  type: "warning"
                });
              }
            });
          }
        } else {
          this.$message({
            message: "提交表单失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    // 删除公司
    deleteCompany(id) {
      if (id != null && id != "") {
        this.$confirm("此操作将永久删除该公司信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            companyApi.deleteCompany(id).then(resp => {
              if (resp.data.flag) {
                this.$message({
                  message: "删除公司信息成功",
                  type: "success"
                });
                this.searchBycompanyName();
                this.radio = "";
              } else {
                this.$message({
                  message: "删除公司信息失败",
                  type: "warning"
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          message: "请选择需要删除的公司哦！",
          type: "warning"
        });
      }
    }
  }
};
</script>

<style lang="css" >
.el-dialog {
  max-height: calc(100% - 200px);
  /* max-height: 600px; */
  display: flex;
  flex-direction: column;
}
.el-dialog__body {
  overflow: auto;
}
</style>

<style lang="css" scoped>
.el-radio__label {
  display: none;
}
/* body .el-table th.gutter {
  display: table-cell !important;
} */
/* .el-table >>> th {
  background-color: #eee;
} */
.el-table >>> td {
  font-size: 13px;
}
</style>